package com.bfxy.rabbitmq.api.exchange.header;

import com.rabbitmq.client.AMQP;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;

import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

public class Sender4HeaderExchange {

    public static void main(String[] args) throws Exception {
        Connection connection = null;
        Channel channel = null;
        try {
            // 1 创建ConnectionFactory
            ConnectionFactory connectionFactory = new ConnectionFactory();
            connectionFactory.setHost("192.168.218.21");
            connectionFactory.setPort(5672);
            connectionFactory.setVirtualHost("/");

            // 2 创建Connection
            connection = connectionFactory.newConnection();

            // 3 创建Channel
            channel = connection.createChannel();

            // 4 声明交换机
            String exchangeName = "test_headers_exchange";
            String exchangeType = "headers";
            channel.exchangeDeclare(exchangeName, exchangeType, true, false, false, null);

            Map<String,Object> headers = new HashMap<>();
            headers.put("format", "pdf");
            headers.put("type", "report");

            // 5 生成发送消息的属性
            AMQP.BasicProperties props = new AMQP.BasicProperties
                    .Builder()
                    .headers(headers)
                    .build();

            // 6 发送消息
            String message = "headers-" + System.currentTimeMillis();
            channel.basicPublish(exchangeName, "", props, message.getBytes(StandardCharsets.UTF_8));
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (channel != null) {
                channel.close();
            }
            if (connection != null) {
                connection.close();
            }
        }
    }

}
